
const titleInput = document.querySelector('.article-title');
const titleLengthInfo = document.querySelector('.title-length-info');
const contentTextarea = document.querySelector('.article-content');
const wordCountSpan = document.querySelector('.article-word-count');
const iconFanhui = document.querySelector('.icon-fanhui');
iconFanhui.addEventListener('click', function () {
    location.href = "/user/recommendPage";
})
// 获取所有标签元素
const tags = document.querySelectorAll('.Essay-classify-contents p');
// 显示标签的元素
const tagLine = document.getElementById('tagLine');
let selectedTagId;
tags.forEach(tag => {
    tag.addEventListener('click', () => {
        // 清除之前所有选中状态
        tags.forEach(t => t.classList.remove('selected'));

        // 添加当前选中状态
        tag.classList.add('selected');

        // 更新显示的内容（直接替换为当前标签）
        tagLine.textContent = tag.textContent;
        selectedTagId = tag.id;
    });
});
// 标题输入框的输入事件处理
titleInput.addEventListener('input', function () {
    const currentLength = this.value.length;
    if (currentLength < 2) {
        titleLengthInfo.textContent = '还需输入' + (2 - currentLength) + '个字';
    } else {
        titleLengthInfo.textContent = '还需输入0个字';
    }
});

// 正文输入框的输入事件处理
contentTextarea.addEventListener('input', function () {
    // 获取纯文本内容（忽略HTML标签）
    const textContent = this.textContent.trim();
    const contentLength = textContent.length;

    // 更新字数统计
    wordCountSpan.textContent = `共 ${contentLength} 字`;

    // 处理占位符显示/隐藏
    const placeholder = this.querySelector('.placeholder');
    if (contentLength === 0 && !placeholder) {
        // 内容为空且没有占位符时，添加占位符
        const placeholderPara = document.createElement('p');
        placeholderPara.className = 'placeholder';
        placeholderPara.textContent = '请输入正文';
        this.appendChild(placeholderPara);
    } else if (contentLength > 0 && placeholder) {
        // 内容不为空但有占位符时，移除占位符
        placeholder.remove();
    }
});
const imageInput = document.getElementById('imageInput');
const addImageBtn = document.getElementById('addImageBtn');
// 给插入图片图标添加点击事件
if (addImageBtn && imageInput) {
    addImageBtn.addEventListener('click', function () {
        imageInput.click(); // 触发文件选择框弹出
    });
}
let contentImageFile = null;
imageInput.addEventListener('change', function (e) {
    const file = e.target.files[0];
    if (file) {
        contentImageFile = file; // 存储图片文件
        updateContentImagePreview(file);
    }
});
// 更新内容图片预览
function updateContentImagePreview(file) {
    const reader = new FileReader();
    reader.onload = function (event) {
        const base64Image = event.target.result;
        const img = document.createElement('img');
        img.src = base64Image;
        img.style.width = '100%';
        img.style.padding = '30px 50px';
        contentTextarea.appendChild(img);

    };
    reader.readAsDataURL(file);
}
// 处理文章封面上传
const imageUpload = document.getElementById('imageUpload');
const imageUploadBox = document.querySelector('.image-upload-box');
imageUpload.addEventListener('change', function (e) {
    // console.log("准备上传文件");
    // console.log('imageUpload元素当前状态:', imageUpload);
    const file = e.target.files[0];
    console.log(file);
    if (file) {
        updateCoverPreview(file);
    }
});

// 更新封面预览
let globalCoverImageFile = null;
function updateCoverPreview(file) {
    // 创建封面图片元素
    const img = document.createElement('img');
    const reader = new FileReader();
    reader.onload = function (event) {
        const base64Image = event.target.result;
        console.log(typeof base64Image);
        img.src = base64Image;
        img.classList.add('cover-image');
        console.log(img.classList);
        // 获取 placeholder 容器
        const placeholder = document.querySelector('.img-placeholder');
        globalCoverImageFile = file;
        if (placeholder) {
            // 清空容器内所有内容
            placeholder.innerHTML = '';
            // 添加图片作为唯一子元素
            placeholder.appendChild(img);
            imageUpload.title = '点击切换图片';
        }
        imageUpload.value = null;
    };
    reader.readAsDataURL(file);
}
//发布文章
const editPostId = localStorage.getItem('editPostId');
// const isEditMode = !!localStorage.getItem('editPostId');
const publishBtn = document.getElementById('publishBtn');
const isDraft=document.querySelector('.Temporarily-save-to-drafts');
const isMemberOnlyCheckbox = document.getElementById('isMemberOnly');
let coverImageFile;
let contentText;
//发文章是的输入判断
function ValidPostContent(){
    // 判空
    if (!titleInput.value.trim()) {
        showMessage('请输入文章标题', 'error');
        titleInput.focus();
        return false;
    }

    if (titleInput.value.length < 2) {
        showMessage('标题至少需要2个字符', 'error');
        titleInput.focus();
        return false;
    }
    // 必须上传封面
    if (!coverImageFile) {
        showMessage('请上传文章封面', 'error');
        return false;
    }
    // 检查是否有内容（除了占位符）
    if (!contentText || contentText === '请输入正文') {
        showMessage('请输入文章内容', 'error');
        contentTextarea.focus();
        return false;
    }
    // 检查是否选择了标签
    if (!selectedTagId) {
        showMessage('请选择文章标签', 'error');
        return false;
    }
    return true;
}

if (editPostId == null) {

    function updateSharedVariables() {
        coverImageFile = globalCoverImageFile;
        contentText = contentTextarea.textContent.trim();
    }
    function submitPost(textStatus) {
        updateSharedVariables();
        if (ValidPostContent()) {
            console.log(contentText)
            // 显示加载状态
            publishBtn.disabled = true;
            publishBtn.textContent = '处理中...';

            const formData = new FormData();
            // 公共参数
            formData.append('title', titleInput.value);
            formData.append('content', contentText);
            formData.append('isMemberOnly', 0);
            formData.append('tagId', selectedTagId);
            formData.append('coverImage', coverImageFile);
            if (contentImageFile) {
                formData.append('picture', contentImageFile);
            }
            // 区分参数：发布状态(1)或草稿(0)
            formData.append('textStatus', textStatus);

            // 发送请求
            $.ajax({
                url: '/NewsController/addNews',
                type: 'POST',
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    console.log("操作成功", response);
                    // 恢复按钮状态
                    publishBtn.disabled = false;
                    publishBtn.textContent = '预览并发布';

                    // 处理成功响应
                    if (response && response.message && response.message.includes('成功')) {
                        const message = textStatus === 0 ? '文章发布成功！' : '草稿保存成功！';
                        showMessage(message, 'success');
                        // 跳转到创作者页面
                        setTimeout(() => {
                            window.location.href = '/creator';
                        }, 1500);
                    } else {
                        showMessage('操作失败：' + (response.message || '未知错误'), 'error');
                    }
                },
                error: function (xhr, status, error) {
                    console.log('请求错误', xhr.status, error);
                    // 恢复按钮状态
                    publishBtn.disabled = false;
                    publishBtn.textContent = '预览并发布';

                    showMessage('操作失败，请重试', 'error');
                }
            });
        }
    }
    // 发布按钮：textStatus=1
    publishBtn.addEventListener('click', () => submitPost(0));

    // 草稿按钮：textStatus=0
    isDraft.addEventListener('click', () => submitPost(1));
}



function showMessage(msg, type = 'error') {
    const messageElement = document.getElementById('alert');
    if (messageElement) {
        messageElement.textContent = msg;
        messageElement.style.color = type === 'success' ? 'green' : 'red';
        messageElement.style.display = 'block';

        setTimeout(() => {
            messageElement.style.display = 'none';
        }, 3000);
    }
}
// 修改文章
if (editPostId) {
    // 使用postId再次调用后端接口回显数据
    $.ajax({
        url: `/getPostById/${editPostId}`,
        type: "GET",
        data: {
            postId: editPostId
        },
        success: function (result) {
            console.log(result);
            // 回显数据
            titleInput.value = result.data.title;
            contentTextarea.textContent = result.data.content;
            if (result.data.picture != null) {
                const picture = document.createElement('img');
                picture.src = result.data.picture;
                picture.style.width = '100%';
                picture.style.padding = '30px 50px';
                contentTextarea.appendChild(picture);
            }
            const placeholder = document.querySelector('.img-placeholder');
            const coverImage = document.createElement('img');
            coverImage.src = result.data.coverImage;
            coverImage.classList.add('cover-image');
            placeholder.innerHTML = '';
            placeholder.appendChild(coverImage);
        },
        error: function (error) {
            console.log(error);
        }
    });
    // 如果使用完后不需要了，也可以移除
    function ValidUpdateContent(){
        // 判空
        if (!titleInput.value.trim()) {
            showMessage('请输入文章标题', 'error');
            titleInput.focus();
            return false;
        }

        if (titleInput.value.length < 2) {
            showMessage('标题至少需要2个字符', 'error');
            titleInput.focus();
            return false;
        }


        // 检查是否有内容（除了占位符）
        if (!contentText || contentText === '请输入正文') {
            showMessage('请输入文章内容', 'error');
            contentTextarea.focus();
            return false;
        }
        // 当用户选择了新图片时上传
        if (contentImageFile) {
            formData.append('picture', contentImageFile);
        }
        //当用户选择了新封面时上传
        if (coverImageFile) {
            formData.append('coverImage', coverImageFile);
        }
        // 检查是否选择了标签
        if (!selectedTagId) {
            showMessage('请选择文章标签', 'error');
            return false;
        }
        return true;
    }
    function updateSharedVariables() {
        coverImageFile = globalCoverImageFile;
        contentText = contentTextarea.textContent.trim();
    }
    function submitUpdate(textStatus){
        console.log("调用成功")
        updateSharedVariables();
        const formData = new FormData();
        if(ValidUpdateContent()){
// 显示加载状态
            publishBtn.disabled = true;
            publishBtn.textContent = '发布中...';
            formData.append('title', titleInput.value);
            formData.append('content', contentText);
            formData.append('isMemberOnly', isMemberOnlyCheckbox.checked ? 1 : 0);
            formData.append('tagId', selectedTagId);
            formData.append('textStatus', textStatus);
            $.ajax({
                url: `/updatePost/${editPostId}`,
                type: "POST",
                processData: false, // 告诉jQuery不要处理数据
                contentType: false,
                data: formData,
                success: function (response) {
                    console.log("发布成功", response);
                    // 恢复按钮状态
                    publishBtn.disabled = false;
                    publishBtn.textContent = '预览并发布';

                    // 处理成功响应
                    if (response && response.message && response.message.includes('成功')) {
                        const message = textStatus === 0 ? '文章发布成功！' : '草稿保存成功！';
                        showMessage(message, 'success');

                        // 跳转到文章列表或详情页（根据实际情况调整）
                        setTimeout(() => {
                            window.location.href = '/creator';
                        }, 1500);
                        localStorage.removeItem('editPostId');

                    } else {
                        showMessage('发布失败：' + (response.message || '未知错误'), 'error');
                    }
                },
                error: function (xhr, status, error) {
                    console.log('请求错误', xhr.status, error);
                    // 恢复按钮状态
                    publishBtn.disabled = false;
                    publishBtn.textContent = '预览并发布';

                    showMessage('发布失败，请重试', 'error');
                }
            })
        }
    }
    // 发布按钮：textStatus=1
    publishBtn.addEventListener('click', () => submitUpdate(0));

    // 草稿按钮：textStatus=0
    isDraft.addEventListener('click', () => submitUpdate(1));
}
